const axios = require('axios')

//send img 
async function send_image() {
  let { data } = await axios.get('https://login.sina.com.cn/sso/qrcode/image?entry=account&size=256&callback=1')
  let reg = /succ/
  if (reg.test(data)){
    let deal_data = data.replace('window.1 && 1(', "").replace(');', "")
    let { data: { qrid, image } } = JSON.parse(deal_data)
    return {qrid, image}
  } else {
    console.log("error");
  }
}



function wait_scan(qrid) {
  return new Promise((resolve, reject) => {
    if (!qrid) {
      return
    }
    try {
      console.log("wait", qrid);
      let date = new Date()
      let t = date.valueOf()
      let url = `https://login.sina.com.cn/sso/qrcode/check?entry=weibo&qrid=${qrid}&callback=STK_${t}`
      // let inValue = setInterval( async() => {

      // }, 5000);
      setTimeout(async () => {
        let { data } = await axios.get(url)
        console.log(data);
        let reg = new RegExp(/"msg":"(.*)",.*"alt":"(.*)"/)
        if (reg.test(data) && RegExp.$1 == 'succ') {
          let alt = RegExp.$2
          console.log("登陆成功..正在获取用户名和用户凭证")
          // clearInterval(inValue)
          let json = {
            alt: alt,
            msg: '登陆成功..正在获取用户名和用户凭证'
          }
          resolve(json)
        }
      }, 20000);

    } catch (error) {
      reject(error)
    }
  })
}

//get cookie
function login(alt) {
  return new Promise((resolve, reject) => {
    try {
      let date = new Date()
      let t = date.valueOf()
      let url = `https://login.sina.com.cn/sso/login.php?entry=weibo&returntype=TEXT&crossdomain=1&cdult=3&domain=weibo.com&alt=${alt}&savestate=30&callback=STK_${t}`
      axios.get(url).then(res => {
        let { data } = res
        data = data.toString().substring("18", data.length - 2)
        data = JSON.parse(data)
        console.log(data);
        let { nick } = data
        console.log(`用户名: ${nick}`);
        let SUB = '_T_WM=65728279763;' + res.headers['set-cookie'][1]
        console.log("cookie:" + SUB);
        let json = {
          sub: SUB,
          sub_msg: nick
        }
        resolve(json)
      })
    } catch (error) {
      reject(error)
    }
  })
}




module.exports = {
  wait_scan,
  login,
  send_image
}


